package myGUI3;

import javax.swing.*; 
import javax.swing.text.NumberFormatter;

import java.util.*;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.awt.*;
import java.awt.Window.*;

import datechooser.*;


public class CalendarGUI3 extends JFrame {
	
	private iCalEvent3 iCalEventEx;
	/////////////////////////////////
	//All the variables that will be on the GUI
	private JLabel eventLabel, locationLabel, commentLabel, resourceLabel, startDateLabel, endDateLabel, priorityLabel, classLabel, dummyLabel;
	private JLabel startTimeLabel, endTimeLabel;
	private JLabel descriptionLabel, recurLabel ;
	private JLabel countLabel, intervalLabel;
	private JTextField eventField, locationField, resourceField, commentField;
	private JFormattedTextField countField, intervalField;
	private JTextArea descriptionArea;
	private JComboBox priorityDropdown, classDropdown, recurDropdown;
	private JButton	clickButton;
	
	//Drop-down Options
	private String priorityOptions[] = {"Low", "Medium", "High"};
	private String priorityChoice;
	
	private String classOptions[] = { "PUBLIC", "PRIVATE", "CONFIDENTIAL"};
	private String classChoice;
	
	private String frequencyOptions[] = {"NONE", "DAILY", "WEEKLY", "MONTHLY", "YEARLY"};
	private String frequencyChoice;
	
	
	
	///For time and date
	private SimpleDateFormat timeFormat = new SimpleDateFormat("HHmmss");
	private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyMMdd");
	private GregorianCalendar gCal 		= new GregorianCalendar();
	private GregorianCalendar today		= new GregorianCalendar(gCal.get(Calendar.YEAR),
																gCal.get(Calendar.MONTH),
																gCal.get(Calendar.DAY_OF_MONTH));
	//Date and Time chooser menus
	private datechooser.beans.DateChooserCombo startDate;
	private datechooser.beans.DateChooserCombo endDate;
	
	private JSpinner startTime, endTime;
	
	//Number format for recurrent event
	
	//NumberFormat  recurFormat =  NumberFormat.getNumberInstance();
	//NumberFormatter recurFormatter = new NumberFormatter(recurFormat);
	//NumberFormat recurTimes = NumberFormat.getNumberInstance();
	//NumberFormatter recurTimesformatter = new NumberFormatter(recurTimes);
	
	
	
	
	private GregorianCalendar gcal		= new GregorianCalendar();
	private Date date					;
	private SpinnerDateModel StartDateModel;
	private SpinnerDateModel EndDateModel;
	
	
	////Output Variables-Used to create the .ics File
	private boolean inputValidity = true;
	private GregorianCalendar todayDate = new GregorianCalendar();
	private String errorMessage = null;
	
	private String eventName = null;
	private String eventLocation = null;
	private String eventResource = null;
	private String eventPriority = null;
	private String eventPrivacy = null;
	private String eventDescription = null;
	//private String eventClass = null;
	private String eventStart = null, eventEnd = null;
	private String eventStartTime = null, eventEndTime = null, eventComment = null;
	private String eventFrequency = null;
	private String eventCount = null;
	private String eventInterval = null;
	
	public CalendarGUI3() {
		Dimension d;
		
		dummyLabel = new JLabel("Place holder for all later!");
		
		eventLabel = new JLabel("Event");
		eventField = new JTextField(40);
		
		descriptionLabel = new JLabel("Description");
		descriptionArea = new JTextArea(5,5);
		
		locationLabel = new JLabel("Location");
		locationField = new JTextField(40);
		
		resourceLabel = new JLabel("Resource");
		resourceField = new JTextField(40);
		
		priorityLabel = new JLabel("Priority");
		priorityDropdown = new JComboBox();
		
		classLabel = new JLabel("Class");
		classDropdown = new JComboBox();
		
		recurLabel = new JLabel("Recurrent");
		recurDropdown = new JComboBox();
		
		commentLabel = new JLabel("Comment");
		commentField = new JTextField(40);
		
		countLabel  = new JLabel("Recur Occurences");
		countField  = new JFormattedTextField("0");
		
		intervalLabel = new JLabel("Interval of Recurrences");
		intervalField = new JFormattedTextField("0");
		
		
		
		/*Start and End Date, Time*/
		startDateLabel = new JLabel("Start Date");
		startDate 	   = new datechooser.beans.DateChooserCombo();
		startDate.setNothingAllowed(false);
		startDate.setBehavior(datechooser.model.multiple.MultyModelBehavior.SELECT_SINGLE);
		startDate.setCurrent(today);
		startDate.setToolTipText("Click to enter date!");
		
		
		endDateLabel  = new JLabel("End Date");
		//endDate.setNothingAllowed(false);
		endDate		= new datechooser.beans.DateChooserCombo();
		endDate.setBehavior(datechooser.model.multiple.MultyModelBehavior.SELECT_SINGLE);
		endDate.setCurrent(today);
		endDate.setToolTipText("Click to enter date!");
		
		
		
		
		//Initialize the start and end times
		gcal.set(Calendar.HOUR_OF_DAY, 0);
		gcal.set(Calendar.MINUTE,0);
		gcal.set(Calendar.SECOND,0);
		date = gcal.getTime();
		StartDateModel = new SpinnerDateModel(date, null, null, Calendar.HOUR_OF_DAY);
		EndDateModel	= new SpinnerDateModel(date, null, null, Calendar.HOUR_OF_DAY);
		
		startTimeLabel = new JLabel("Start Time");
		startTime 	   = new JSpinner(StartDateModel);
		JSpinner.DateEditor startDateFormat  = new JSpinner.DateEditor(startTime, "h:mm a");
		startTime.setEditor(startDateFormat);
		
		endTimeLabel   = new JLabel("End Time");
		endTime 	   = new JSpinner(EndDateModel);
		JSpinner.DateEditor endDateFormat = new JSpinner.DateEditor(endTime, "h:mm a");
		endTime.setEditor(endDateFormat);
		
		
		
		
		
		d = dummyLabel.getPreferredSize();
		//Construct up the labels and field		
		eventLabel.setPreferredSize(new Dimension(d.width + 10, d.height));
		eventField.addActionListener(new java.awt.event.ActionListener() 
		{
			public void actionPerformed(java.awt.event.ActionEvent evt) 
			{
				eventFieldActionPerformed(evt);
			}
		}
		);
		
		locationLabel.setPreferredSize(new Dimension(d.width + 10, d.height));
		locationField.setPreferredSize(new Dimension(d.width + 10, d.height));
		locationField.addActionListener(new java.awt.event.ActionListener()
		{
			public void actionPerformed(java.awt.event.ActionEvent evt)
			{
				locationFieldActionPerformed(evt);
			}
		});
		
		commentLabel.setPreferredSize(new Dimension(d.width + 10, d.height));
		commentField.setPreferredSize(new Dimension(d.width + 10, d.height));
		commentField.addActionListener(new java.awt.event.ActionListener()
		{
			public void actionPerformed(java.awt.event.ActionEvent evt)
			{
				commentFieldActionPerformed(evt);
			}
		});
		
		
		resourceLabel.setPreferredSize(new Dimension(d.width + 10, d.height));
		resourceField.setPreferredSize(new Dimension(d.width + 10, d.height));
		resourceField.addActionListener( new java.awt.event.ActionListener()
		{
			public void actionPerformed(java.awt.event.ActionEvent evt)
			{
				resourceFieldActionPerformed(evt);
			}
			
		});
		
		priorityLabel.setPreferredSize(new Dimension(d.width + 10, d.height));
		priorityDropdown.setMaximumRowCount(3);
		priorityDropdown.setModel(new DefaultComboBoxModel(priorityOptions));
		priorityDropdown.addActionListener( new java.awt.event.ActionListener()
		{
			public void actionPerformed(java.awt.event.ActionEvent evt)
			{
				priorityDropdownFieldActionPerformed(evt);
			}
			
		});
		
		classLabel.setPreferredSize(new Dimension(d.width + 10, d.height));
		classDropdown.setMaximumRowCount(3);
		classDropdown.setModel(new DefaultComboBoxModel(classOptions));
		classDropdown.addActionListener( new java.awt.event.ActionListener()
		{
			public void actionPerformed(java.awt.event.ActionEvent evt)
			{
				optionDropdownFieldActionPerformed(evt);
			}
			
		});
		
		
		startDateLabel.setPreferredSize(new Dimension(d.width + 10, d.height));
		startDate.setPreferredSize(new Dimension(d.width + 10, d.height));
		
		
		endDateLabel.setPreferredSize(new Dimension(d.width + 10, d.height));
		endDate.setPreferredSize(new Dimension(d.width + 10, d.height));
		
		startTimeLabel.setPreferredSize(new Dimension(d.width + 10, d.height));
		startTime.setPreferredSize(new Dimension(d.width + 10, d.height)); 
		
		endTimeLabel.setPreferredSize(new Dimension(d.width + 10, d.height));
		endTime.setPreferredSize(new Dimension(d.width + 10, d.height));
		
		recurLabel.setPreferredSize(new Dimension(d.width + 10, d.height));
		recurDropdown.setModel(new DefaultComboBoxModel(frequencyOptions));
		recurDropdown.setMaximumRowCount(5);
		recurDropdown.addActionListener(new java.awt.event.ActionListener()
		{
			public void actionPerformed(java.awt.event.ActionEvent evt) 
			{
				recurDropdownFieldActionPerformed(evt);
			}
		});
		
		countLabel.setPreferredSize(new Dimension(d.width + 10, d.height));
		countField.setPreferredSize(new Dimension(d.width + 10, d.height));
		countField.addActionListener(new java.awt.event.ActionListener()
		{
			public void actionPerformed(java.awt.event.ActionEvent evt)
			{
				countFieldActionPerformed(evt);
			}
		});
		
		intervalLabel.setPreferredSize(new Dimension(d.width + 10, d.height));
		intervalField.setPreferredSize(new Dimension(d.width + 10, d.height));
		intervalField.addActionListener(new java.awt.event.ActionListener()
		{
			public void actionPerformed(java.awt.event.ActionEvent evt)
			{
				intervalFieldActionPerformed(evt);
			}
		});
		
		
		
		descriptionLabel.setPreferredSize(new Dimension(d.width+ 10, d.height));
		descriptionArea.setPreferredSize(new Dimension(d.width + 10, d.height));
		
		clickButton = new JButton("Create Event");
		
		clickButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                clickButtonMouseClicked(evt);
            }
        });
		
		clickButton.addActionListener(new java.awt.event.ActionListener()
		{
			public void actionPerformed(java.awt.event.ActionEvent evt) 
			{
				clickButtonActionPerformed(evt);
			}
		}
		);
	
	}
	
	public static void main(String[] args) {
		CalendarGUI3 ex = new CalendarGUI3();
		ex.createWindow();
	}
	
	private void createWindow(){
		
		JFrame mainWindow = new JFrame("CALENDAR");
		mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		mainWindow.setContentPane(createLayout());
		mainWindow.pack();
		mainWindow.setVisible(true);
	}
	
	private JPanel createLayout() {
		JPanel windowContent = new JPanel();
		windowContent.setLayout(new BoxLayout(windowContent, BoxLayout.Y_AXIS));
		
		Box temp = Box.createHorizontalBox();
        temp.add(eventLabel);
        temp.add(eventField);
        windowContent.add(temp);
        
        Component space =  Box.createVerticalStrut(10);
        windowContent.add(space);
        
        temp = Box.createHorizontalBox();
        temp.add(locationLabel);
        temp.add(locationField);
        windowContent.add(temp);
        
        space = Box.createVerticalStrut(10);
        windowContent.add(space);
        
        temp = Box.createHorizontalBox();
        temp.add(commentLabel);
        temp.add(commentField);
        windowContent.add(temp);
        
        space = Box.createVerticalStrut(10);
        windowContent.add(space);
        
        temp = Box.createHorizontalBox();
        temp.add(resourceLabel);
        temp.add(resourceField);
        windowContent.add(temp);
        
        space = Box.createVerticalStrut(10);
        windowContent.add(space);
        
        temp = Box.createHorizontalBox();
        temp.add(priorityLabel);
        temp.add(priorityDropdown);
        windowContent.add(temp);
        
        space = Box.createVerticalStrut(10);
        windowContent.add(space);
        
        temp = Box.createHorizontalBox();
        temp.add(classLabel);
        temp.add(classDropdown);
        windowContent.add(temp);
        
        space = Box.createVerticalStrut(10);
        windowContent.add(space);
        
        temp = Box.createHorizontalBox();
        temp.add(startDateLabel);
        temp.add(startDate);
        windowContent.add(temp);
        
        space = Box.createVerticalStrut(10);
        windowContent.add(space);
        
        temp = Box.createHorizontalBox();
        temp.add(endDateLabel);
        temp.add(endDate);
        windowContent.add(temp);
        
        space = Box.createVerticalStrut(10);
        windowContent.add(space);
        
        temp = Box.createHorizontalBox();
        temp.add(startTimeLabel);
        temp.add(startTime);
        windowContent.add(temp);
        
        space = Box.createVerticalStrut(10);
        windowContent.add(space);
        
        temp = Box.createHorizontalBox();
        temp.add(endTimeLabel);
        temp.add(endTime);
        windowContent.add(temp);
        
        space = Box.createVerticalStrut(15);
        windowContent.add(space);
        
        temp = Box.createHorizontalBox();
        temp.add(recurLabel);
        temp.add(recurDropdown);
        windowContent.add(temp);
        
        space = Box.createVerticalStrut(15);
        windowContent.add(space);
        
        temp = Box.createHorizontalBox();
        temp.add(countLabel);
        temp.add(countField);
        windowContent.add(temp);
        
        space = Box.createVerticalStrut(15);
        windowContent.add(space);
        
        temp = Box.createHorizontalBox();
        temp.add(intervalLabel);
        temp.add(intervalField);
        windowContent.add(temp);
        
        space = Box.createVerticalStrut(15);
        windowContent.add(space);
        
        
        temp = Box.createHorizontalBox();
        temp.add(descriptionLabel);
        temp.add(descriptionArea);
        windowContent.add(temp);
        
        space = Box.createVerticalStrut(20);
        windowContent.add(space);
        
        windowContent.add(clickButton);
        space = Box.createVerticalStrut(20);
        windowContent.add(space);
        
        
        
        return windowContent;
		
	
	}
	
	private void eventFieldActionPerformed(java.awt.event.ActionEvent evt) {}
	
	private void locationFieldActionPerformed(java.awt.event.ActionEvent evt) {}
	
	private void resourceFieldActionPerformed(java.awt.event.ActionEvent evt) {}
	
	private void priorityDropdownFieldActionPerformed(java.awt.event.ActionEvent evt) {}
	
	private void optionDropdownFieldActionPerformed(java.awt.event.ActionEvent evt) {}
	
	private void intervalFieldActionPerformed(java.awt.event.ActionEvent evt) {}
	
	private void countFieldActionPerformed(java.awt.event.ActionEvent evt) {}
	
    private void clickButtonMouseClicked(java.awt.event.MouseEvent evt) {}//GEN-FIRST:event_createButtonMouseClicked};

    private void commentFieldActionPerformed(java.awt.event.ActionEvent evt) {}
    
    private void recurDropdownFieldActionPerformed(java.awt.event.ActionEvent evt){}
    
    
    
    private void resetCalendar()
    {	eventField.setText("");
    	locationField.setText("");
    	resourceField.setText("");
    	descriptionArea.setText("");
    	commentField.setText("");
    	errorMessage = "";
    	countField .setText("0");
    	intervalField.setText("0");
    	
    	startDate.setSelectedDate(today);
    	endDate.setSelectedDate(today);
    	
    	startTime.getModel().setValue(date);
    	endTime.getModel().setValue(date);
    	
    	
    	
    }
    private boolean checkInput() {
    	///Checking start date
    	Calendar timeStartInput = new GregorianCalendar();
    	Calendar timeEndInput = new GregorianCalendar();
    	if ( startDate.getSelectedDate().get(Calendar.YEAR) >= todayDate.get(Calendar.YEAR))
    	{
    		
    		if(startDate.getSelectedDate().get(Calendar.DAY_OF_YEAR) < todayDate.get(Calendar.DAY_OF_YEAR))
    				{
    					//System.out.println(startDate.getSelectedDate().get(Calendar.DAY_OF_YEAR));
    					//System.out.println(todayDate.get(Calendar.DAY_OF_YEAR));
    					errorMessage = "ERROR! Start Date already happened";
    					inputValidity = false;
    				}
    		
    	}
    	
    	else {inputValidity = false; return inputValidity;};
    	
    	////Checking dateStart happens before dateEnd
    	if ( endDate.getSelectedDate().get(Calendar.YEAR) >= todayDate.get(Calendar.YEAR))
    	{
    		
    		if(endDate.getSelectedDate().get(Calendar.DAY_OF_YEAR) < startDate.getSelectedDate().get(Calendar.DAY_OF_YEAR))
    				{
    					//System.out.println(endDate.getSelectedDate().get(Calendar.DAY_OF_YEAR));
    					//System.out.println(todayDate.get(Calendar.DAY_OF_YEAR));
    					errorMessage = "ERROR! End Date already happenned!";
    					inputValidity = false;
    				}
    		
    	}
    	
    	else {inputValidity = false; return inputValidity;};
    	
    	////Check if dateStart happens before dateEnd
    	
    		
    		
    	timeStartInput.setTime((Date) startTime.getValue());
    	timeEndInput.setTime((Date) endTime.getValue());
    		
    	if (timeStartInput.get(Calendar.HOUR_OF_DAY) < timeEndInput.get(Calendar.HOUR_OF_DAY))
    		{
    			if (timeStartInput.get(Calendar.MINUTE) >= timeEndInput.get(Calendar.MINUTE))
    				{
    					//errorMessage = "ERROR! Ending Time happens before Starting Time";
    					//inputValidity = false;
    				}
    		}
    	else 
    	{
    		errorMessage = "ERROR! Ending Time happens before or simultaneously with Starting Time";
    		inputValidity = false; return inputValidity;
    	}
    	
    	try{
    			Integer.parseInt(countField.getText());
    			Integer.parseInt(intervalField.getText());
    	}
    	catch (Exception e)
    	{
    		errorMessage = "ERROR! Please enter a non-negative integer for count or interval of recurrent occurences!";
    		inputValidity = false; return inputValidity;
    	}
    	
    	if (recurDropdown.getSelectedItem() == "NONE" & Integer.parseInt(countField.getText()) != 0)
    	{
    		errorMessage = "ERROR! Count of recurrent occurences must be zero if the event is NOT recurrent!";
    		inputValidity = false; return inputValidity;
    	}
    	
    	if (recurDropdown.getSelectedItem() == "NONE" & Integer.parseInt(intervalField.getText()) != 0)
    	{
    		errorMessage = "ERROR! Interval between occurences must be zero if the event is NOT recurrent!";
    		inputValidity = false; return inputValidity;
    	}
    	
    	
    	return 	inputValidity;
    };
    
	private void clickButtonActionPerformed(java.awt.event.ActionEvent evt)
	{
		eventName = this.eventField.getText();
		eventLocation = this.locationField.getText();
		eventResource = this.resourceField.getText();
		eventDescription = this.descriptionArea.getText();
		eventComment = this.commentField.getText();
		
		
		priorityChoice = this.priorityDropdown.getSelectedItem().toString().toUpperCase();
		eventPriority = priorityChoice;
		
		classChoice = this.classDropdown.getSelectedItem().toString();
		eventPrivacy = this.classChoice;
		
		frequencyChoice = this.recurDropdown.getSelectedItem().toString().toUpperCase();
		eventFrequency = this.frequencyChoice;
		
		eventCount = this.countField.getText().toUpperCase();
		eventInterval = this.intervalField.getText().toUpperCase();
		
		/*if (priorityChoice == "None")		eventPriority = "0";
		else if (priorityChoice == "Low") 	eventPriority = "9";
		else if (priorityChoice == "Medium")eventPriority = "5";
		else 								eventPriority = "1";
		*/
		
		
		
		eventStart = dateFormat.format(this.startDate.getCurrent().getTime());
		eventEnd   = dateFormat.format(this.endDate.getCurrent().getTime());
		
		eventStartTime = timeFormat.format(startTime.getValue());
		eventEndTime   = timeFormat.format(endTime.getValue());
		
		if (this.checkInput())
		{
		
		
		iCalEventEx = new iCalEvent3(eventName, eventStart, eventEnd, eventStartTime,
                eventEndTime, eventLocation, eventComment, eventResource, eventPrivacy, eventPriority, eventFrequency, eventCount, eventInterval, eventDescription);
		
		//System.out.println(eventStart);///TO BE COMMENTED OUT
		//System.out.println(eventEnd);//TO BE COMMENTED
		
		
		
		if (iCalEventEx.createFile()) 
			JOptionPane.showMessageDialog(this, "Success!");
		
		System.out.println(iCalEventEx.getContent());
		} 
		
		else
		{	
		JOptionPane.showMessageDialog(null, errorMessage);
		this.inputValidity = true;
		
		
		}
		
		this.resetCalendar();
		
		
		
		
		
	}

	

}

